package com.zijidelu.luframework.starter.scanner;

import cn.hutool.core.util.StrUtil;
import com.zijidelu.luframework.utils.spring.beans.register.SpringSimpleBeanUtil;
import com.zijidelu.luframework.config.properties.LuFrameworkProperties;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 自动扫描器工厂
 *
 * @author ZIJIDELU
 * @datetime 2025/10/28 19:56
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AutoScannerFactory implements SmartInitializingSingleton {
    private final DefaultListableBeanFactory beanFactory;
    private final LuFrameworkProperties luFrameworkProperties;
    private final SpringSimpleBeanUtil springSimpleBeanUtil;
    private final AtomicBoolean initialized = new AtomicBoolean(false);

    /**
     * 扫描器列表，方便统一管理资源
     */
    private final List<AbstractAutoScanner> scanners = new ArrayList<>();

    /**
     * {@inheritDoc}
     */
    @Override
    public void afterSingletonsInstantiated() {
        if (!initialized.compareAndSet(false, true)) {
            log.warn("[AutoScannerFactory] is already initialized, skipping duplicate execution.");
            return;
        }

        log.info("[AutoScannerFactory] => Starting auto-scanner initialization...");

        try {

            if (!luFrameworkProperties.getAuto().isEnableAutoScanner()) {
                log.info("[AutoScannerFactory] => Auto-scanner is disabled.");
                return;
            }

            final List<AbstractAutoScanner> sortedScanners = SingleDependencyScannerSorter.sort(springSimpleBeanUtil.getBeansOfType(AbstractAutoScanner.class));
            scanners.addAll(sortedScanners);
            if (CollectionUtils.isEmpty(scanners)) {
                log.info("[AutoScannerFactory] => No scanners found.");
                return;
            }

            // 执行所有扫描器
            executeAll();

            log.info("[AutoScannerFactory] => All scanners executed successfully.");
        } catch (Exception e) {
            log.error("[AutoScannerFactory] => Scanner initialization failed: {}", e.getMessage());
            throw new IllegalStateException(
                    "[AutoScannerFactory] => Initialization failed, startup aborted. See logs for details.", e);
        } finally {
            // 自动销毁资源
            destroy();
        }
    }

    /**
     * 执行扫描
     */
    private void executeAll() {
        // 执行扫描
        scanners.forEach(scanner -> {
            log.info("[AutoScannerFactory] => Executing scanner: {}", scanner.getScannerName());
            scanner.init();
        });
    }

    /**
     * 销毁方法，在BeanFactory关闭时调用
     */
    public void destroy() {
        // 扫描完成后，清空列表以释放引用
        scanners.clear();
        AbstractAutoScanner.clearCache();
        // 销毁扫描器工厂Bean
        String beanName = StrUtil.lowerFirst(this.getClass().getSimpleName());
        if (beanFactory.containsBeanDefinition(beanName)) {
            beanFactory.destroySingleton(beanName); // 销毁单例实例
            beanFactory.removeBeanDefinition(beanName); // 移除定义
            log.info("[AutoScannerFactory] => Bean '{}' destroyed and definition removed.", beanName);
        }
    }

    /**
     * 条件注册扫描器
     *
     * @param enabled 是否启用
     * @param scanner 扫描器实例
     */
    private void registerScannerIfEnabled(boolean enabled, @NonNull AbstractAutoScanner scanner) {
        if (!enabled) return;
        // 注入依赖
        SpringSimpleBeanUtil.autowire(scanner);
        // 添加到管理列表
        scanners.add(scanner);
        log.debug("[AutoScannerFactory] => Registered scanner: {}", scanner.getClass().getSimpleName());
    }

}

